package com.slfx.open.api.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.slfx.open.api.entity.OpenInterface;
import com.slfx.open.api.handle.RestTemplateHandle;
import com.slfx.open.api.sdk.common.exception.CommonException;
import com.slfx.open.api.sdk.common.exception.ErrorCodeEnum;
import com.slfx.open.api.service.OpenInterfaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * @author zengqingfa
 * @className OpenApiController
 * @description
 * @create 2022/9/25 16:42
 */
@RestController
@Slf4j
@RequestMapping("/opi")
public class OpenApiController {

    @Resource
    private RestTemplateHandle restTemplateHandle;
    @Resource
    private OpenInterfaceService openInterfaceService;

    /**
     * 统一处理所有的请求,发起第三方的调用,然后返回
     *
     * @return
     */
    @RequestMapping(value = "/**", method = {RequestMethod.POST, RequestMethod.GET})
    public Object call(HttpServletRequest request, HttpServletResponse response
            , @RequestBody(required = false) String bizContent //post请求接收的参数
            , @RequestParam(required = false) Map<String, Object> paramMap//get请求接收的参数封装
            , @RequestParam(required = false) MultiValueMap<String, Object> param//如果是GET请求就尾巴，如果是post接受尾巴和form表单 TODO
            , @RequestPart(required = false) List<MultipartFile> files //文件数组 TODO
    ) {
        //这里发起第三方系统的调用
        String requestURI = request.getRequestURI();
        //获取到尾部地址，发起调用
        String[] split = requestURI.split("opi");
        OpenInterface openInterface = openInterfaceService.getOne(new LambdaQueryWrapper<OpenInterface>()
                .eq(OpenInterface::getRequestTailUrl, split[1])
                .last("limit 1"));
        if (Objects.isNull(openInterface)) {
            throw new CommonException(ErrorCodeEnum.ERROR_NOT_FIND_USER_BY_ID);
        }
        String requestMethod = openInterface.getRequestMethod();
        //获取所有请求头名称
        Map<String, String> headerMap = new HashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            headerMap.put(name, request.getHeader(name));
        }
        Object result = null;
        if ("GET".equalsIgnoreCase(requestMethod)) {
            result = restTemplateHandle.getObject(openInterface.getRequestUrl(), headerMap, JSON.toJSONString(paramMap), Object.class);
        } else if ("POST".equalsIgnoreCase(requestMethod) && "json".equals(openInterface.getRequestPostType())) {
            result = restTemplateHandle.postToJson(openInterface.getRequestUrl(), headerMap, bizContent, Object.class);
        }
        return result;
    }


}